package com.walter.controller;

import com.walter.AuthService;
import com.walter.annotation.SysLog;
import com.walter.common.Result;
import com.walter.exception.LogicException;
import com.walter.model.form.LoginForm;
import com.walter.service.DayVisitService;
import com.walter.util.ValidationUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

/**
 * @author ：ch
 * @date ：Created in 2021/5/25
 * @description：
 * @modified By：
 * @version: 1.0
 */
@Controller
@RequestMapping("/api/auth")
@Slf4j
public class AuthController {
    @Autowired
    private AuthService authService;

    @Autowired
    private DayVisitService dayVisitService;

    @PostMapping("login")
    @ResponseBody
    @ApiOperation("登录")
    @SysLog("登录")
    public Result<String> login(@Valid @RequestBody LoginForm loginForm){
        ValidationUtils.validateEntity(loginForm);
        try {
            final String token = authService.login(loginForm.getUserName(), loginForm.getPassword());
            String tokenPrefix = "Bearer ";// 配置文件 todo
            // Return the token
            dayVisitService.insertRecord(); // 记录访问
            return Result.success(tokenPrefix + token);
        }
        catch (AuthenticationException e){
            log.info("login error:\n",e);
            throw new LogicException("用户名或密码错误");
        }
    }

}
